<template>
  <div><!--行内表单-->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getRoleTable">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addHandler" v-if="hasAuth('sys:role:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定批量删除选中的项目吗？" @confirm="delHandler(null)">
          <el-button slot="reference" type="danger" :disabled="deleteStatus" v-if="hasAuth('sys:role:delete')">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!--可选中表格-->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      stripe
      border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="名称" width="120"></el-table-column>
      <el-table-column prop="code" label="唯一编码" show-overflow-tooltip></el-table-column>
      <el-table-column prop="remark" label="描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.status===1" type="success">正常</el-tag>
          <el-tag size="small" v-else-if="scope.row.status===0" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="permHandler(scope.row.id)">分配权限</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm title="确定删除吗？" @confirm="delHandler(scope.row.id)">
              <el-button slot="reference" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="current"
      :page-size="size"
      :total="total">
    </el-pagination>

    <!--新增按钮的对话框-->
    <el-dialog :close-on-click-modal="false" title="请输入信息" :visible.sync="dialogVisible" width="600px">
      <!--对话框中的表单-->
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-editForm">

        <el-form-item label="角色名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一编码" prop="code" label-width="100px">
          <el-input v-model="editForm.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="editForm.status">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>正常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editForm')">提交</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--分配权限对话框-->
    <el-dialog
      :close-on-click-modal="false"
      title="分配权限"
      :visible.sync="dialogVisible_perm"
      width="600px">

      <el-form :model="editForm">
        <el-tree
          :data="permTreedata"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          ref="permTree"
          check-strictly
          default-expand-all>
        </el-tree>
      </el-form>

      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogVisible_perm = false">取 消</el-button>
        <el-button type="primary" @click="submitPermFormHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
      name: "RoleManage",
      data(){
        return {
          deleteStatus:true, //批量删除按钮的可点击状态，无选中时不可点击批量删除
          dialogVisible: false, //对话框默认不显示
          dialogVisible_perm:false,//分配权限对话框的显示状态
          total:0,
          size:10,
          current:1,
          editForm:{},
          permForm:{},
          tableData:[],
          multipleSelection:[], //表格中勾选上的项目
          editFormRules: {
            name: [
              {required: true, message: '请输入角色名称', trigger: 'blur'}
            ],
            code: [
              {required: true, message: '请输入唯一编码', trigger: 'blur'}
            ],
            status: [
              {required: true, message: '请选择状态', trigger: 'blur'}
            ]
          },
          searchForm:{
            name:""
          },
          permTreedata: [], //树形控件的数据
          defaultProps: {   //树形控件子节点和结点标签的默认名称
            children: 'children',
            label: 'name'
          }
        }
      },
      created() {
        this.getRoleTable();  //获取角色列表

        this.axios.get("/sys/menu/list").then(res=>{  //获取可分配的菜单权限
          this.permTreedata = res.data.data;
        })
      },
      methods: {
        toggleSelection(rows) {
          if (rows) {
            rows.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row);
            });
          } else {
            this.$refs.multipleTable.clearSelection();
          }
        },
        handleSelectionChange(val) {
          this.deleteStatus = val.length === 0; //没有被选中的项目时设置批量删除按钮不可选中
          this.multipleSelection = val;
        },
        handleSizeChange(val) { //每页显示的条数改变时执行，页码功能，改变每页显示条数
          this.size = val;
          this.getRoleTable();
        },
        handleCurrentChange(val) {  //页码变动时执行，页码功能，切换页码
          this.current = val;
          this.getRoleTable();
        },
        getRoleTable() {  //获取角色列表
          this.axios.get("/sys/role/list", {
            params: {
              name: this.searchForm.name,
              current: this.current,
              size: this.size
            }
          }).then(res => {
            this.tableData = res.data.data.records;
            this.size = res.data.data.size;
            this.current = res.data.data.current;
            this.total = res.data.data.total;
          })
        },
        resetForm(formName) {
          this.editForm = {};
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.axios.post('/sys/role/' + (this.editForm.id ? 'update' : 'save'), this.editForm).then(res => {
                this.getRoleTable();
                this.$message({
                  showClose: true,
                  message: '操作成功',
                  type: 'success',
                  onClose: () => { //消息框关闭时的回调函数
                  }
                });
              })
              this.dialogVisible = false;
            } else {
            }
          });
        },
        editHandle(id) {  //编辑操作
          this.axios.get("/sys/role/info/" + id).then(res => {
            this.editForm = res.data.data;
            this.dialogVisible = true;
          })
        },
        addHandler() {  //添加操作
          this.resetForm();
          this.dialogVisible = true;
        },
        resetForm(formName) {
          this.editForm = {};
        },
        delHandler(id) {  //删除操作
          let idArr = [];
          if (id) {   //id有值为单条删除
            idArr.push(id)
          } else {   //id无值为批量删除
            this.multipleSelection.forEach(row => {
              idArr.push(row.id);
            })
          }
          this.axios.post("/sys/role/delete/", idArr).then(res => {
            this.getRoleTable();
            this.$message({
              showClose: true,
              message: '删除成功',
              type: 'success',
              onClose: () => { //消息框关闭时的回调函数
              }
            });
          })
        },
        permHandler(id) { //分配权限
          this.dialogVisible_perm = true;  //打开对话框
          this.axios.get("/sys/role/info/"+id).then(res=>{
            this.$refs.permTree.setCheckedKeys(res.data.data.menuIds);  //已有的权限默认选中
            this.permForm = res.data.data;  //方便提交时的操作，通过this.permForm.id获取要修改的角色
          })
        },
        submitPermFormHandler(){  //提交分配权限表单
          this.dialogVisible_perm = false;  //关闭对话框
          let menuIds = this.$refs.permTree.getCheckedKeys(); //获取树中被选中节点的id
          this.axios.post("/sys/role/perm/"+this.permForm.id,menuIds).then(res=>{  //修改权限后的信息提交到后台
            this.getRoleTable();
            this.$message({
              showClose: true,
              message: '分配权限成功',
              type: 'success',
              onClose: () => { //消息框关闭时的回调函数
              }
            });
          })
        }
      },
    }
</script>

<style scoped>
.el-pagination{
  float: right;
  margin-top: 16px;
}
</style>
